package com.example.javaservice.controller;

import com.example.javaservice.common.Result;
import com.example.javaservice.pojo.Post;
import com.example.javaservice.service.PostService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/posts")
public class PostController {

    private final PostService postService;

    public PostController(PostService postService) {
        this.postService = postService;
    }

    /** 发帖接口（默认 pending） */
    @PreAuthorize("hasAnyRole('USER','ADMIN')")
    @PostMapping("/create")
    public Result<?> createPost(@RequestBody Post post) {
        boolean ok = postService.createPost(post);
        if (ok) {
            return Result.success("发帖成功，等待审核");
        } else {
            return Result.error("发帖失败");
        }
    }

    /** 管理员审核通过 */
    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/approve/{id}")
    public Result<?> approve(@PathVariable Integer id) {
        boolean ok = postService.approvePost(id);
        if (ok) {
            return Result.success("审核通过");
        } else {
            return Result.error("审核失败");
        }
    }

    /** 管理员拒绝 */
    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/reject/{id}")
    public Result<?> reject(@PathVariable Integer id) {
        boolean ok = postService.rejectPost(id);
        if (ok) {
            return Result.success("已拒绝");
        } else {
            return Result.error("操作失败");
        }
    }
    /**✅ 管理员查看所有帖子（含 pending / approved / rejected） */
    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/admin/list")
    public Result<List<Post>> adminList() {
        List<Post> posts = postService.findAll();
        return Result.success("查询成功", posts);
    }
    /** 用户可见帖子（只显示已审核的） */
    @GetMapping("/approved")
    public Result<List<Post>> getApprovedPosts() {
        List<Post> posts = postService.findAllApproved();
        return Result.success("查询成功", posts);
    }

    /** 🧩 查看单篇文章详情（只允许看 approved 的） */
    @GetMapping("/{id}")
    public Result<Post> getPostById(@PathVariable Integer id) {
        Post post = postService.findById(id);
        if (post == null) {
            return Result.error("文章不存在");
        }
        if (!"approved".equals(post.getStatus())) {
            return Result.error("该文章未审核通过");
        }
        postService.increaseViews(id);
        return Result.success("查询成功", post);
    }
    /**搜索**/
    @GetMapping("/search")
    public Result<List<Post>> searchPosts(@RequestParam String keyword) {
        List<Post> list = postService.searchPosts(keyword);
        return Result.success(list);
    }

}
